package by.home;

import by.home.exceptions.OutOfMapBordersException;
import by.home.exceptions.PlacingOnMapException;

public class EnvironmentFactory implements PositionInspector{

  private Point[][] treasureMap = null;

  public EnvironmentFactory(int mapSizeX, int mapSizeY) {
    treasureMap = new Point[mapSizeX][mapSizeY];
    for (int i = 0; i < mapSizeX; i++) {
      for (int j = 0; j < mapSizeY; j++) {
        treasureMap[i][j] = new Sand(i, j);
      }
    }
  }

  public Point[][] getTreasureMap() {
    return treasureMap;
  }

  public TreasureFinder createTreasureFinder(int finderPositionX, int finderPositionY) throws OutOfMapBordersException, PlacingOnMapException {
    if (isOnMap(finderPositionX, finderPositionY)) {
      if (isEmptyPosition(finderPositionX, finderPositionY)) {
        TreasureFinder treasureFinder = new TreasureFinder(finderPositionX, finderPositionY, treasureMap);
        treasureMap[finderPositionX][finderPositionY] = treasureFinder;
        return treasureFinder;
      } else {
        throw new PlacingOnMapException();
      }
    } else {
      throw new OutOfMapBordersException();
    }
  }

  public boolean isEmptyPosition(int posX, int posY) {
    return treasureMap[posX][posY].isPassable();
  }

  public boolean isOnMap(int posX, int posY) {
    return posX < treasureMap.length && posY < treasureMap[1].length;
  }

  public void createTreasure(int treasurePositionX, int treasurePositionY) throws PlacingOnMapException, OutOfMapBordersException {
    if (isOnMap(treasurePositionX, treasurePositionY)) {
      if (isEmptyPosition(treasurePositionX, treasurePositionY)) {
        Treasure treasure = new Treasure(treasurePositionX, treasurePositionY);
        treasureMap[treasurePositionX][treasurePositionY] = treasure;
      } else {
        throw new PlacingOnMapException();
      }
    } else {
      throw new OutOfMapBordersException();
    }
  }

  public void createMountains(int amount) {
    int i = 1, posX, posY;
    while (i <= amount) {
      posX = (int) (Math.random() * 10);
      posY = (int) (Math.random() * 10);
      if (isOnMap(posX, posY) && isEmptyPosition(posX, posY)) {
        treasureMap[posX][posY] = new Mountain(posX, posY);
        i++;
      }
    }
  }

}

